<template>
  <div class="container mx-auto px-4 py-8">
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold">分享</h1>
      <el-button type="primary" @click="$router.push('/share/comment-wall')">
        <el-icon class="mr-2"><ChatLineSquare /></el-icon>
        校园评论墙
      </el-button>
    </div>

    <!-- 顶部操作栏 -->
    <div class="flex flex-wrap gap-4 items-center justify-between mb-8">
      <div class="flex items-center gap-4">
        <el-input
          v-model="searchQuery"
          placeholder="搜索分享..."
          class="w-64 search-input"
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />
        <el-select
          v-model="selectedTags"
          multiple
          collapse-tags
          collapse-tags-tooltip
          placeholder="选择标签"
          class="w-64 tag-select"
        >
          <el-option
            v-for="tag in tagOptions"
            :key="tag.tagId"
            :label="tag.tagName"
            :value="tag.tagId"
          />
        </el-select>
      </div>
      <el-button 
        type="primary" 
        class="publish-btn !bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700
               border-0 shadow-lg shadow-blue-500/20"
        @click="handlePublishClick"
      >
        <el-icon class="mr-1"><Plus /></el-icon>发布分享
      </el-button>
    </div>

    <!-- 内容列表 -->
    <div v-loading="loading" class="grid grid-cols-1 gap-6">
      <el-empty v-if="shareList.length === 0" description="暂无数据" />
      
      <el-card 
        v-for="share in shareList" 
        :key="share.shareId" 
        class="post-card hover:shadow-lg transition-all duration-300 transform hover:-translate-y-1
               bg-gradient-to-br from-gray-50 to-white border border-gray-200/50"
        @click="navigateToDetail(share.shareId)"
      >
        <div class="flex items-start gap-4">
          <!-- 用户信息 -->
          <div class="flex-shrink-0">
            <el-avatar 
              :size="48" 
              :src="getUserAvatar(share)"
              @click.stop="navigateToUserProfile(share.userId)"
              class="cursor-pointer hover:ring-2 hover:ring-blue-500 transition-all duration-300"
            />
          </div>

          <!-- 帖子内容 -->
          <div class="flex-grow">
            <div class="flex items-center justify-between mb-2">
              <div>
                <span 
                  class="font-semibold hover:text-blue-600 cursor-pointer"
                  @click.stop="navigateToUserProfile(share.userId)"
                >
                  {{ share.createBy }}
                </span>
              </div>
              <span class="text-gray-500 text-sm">{{ formatTime(share.createTime) }}</span>
            </div>

            <p class="text-gray-600 mb-4 line-clamp-3">{{ share.content }}</p>

            <!-- 标签 -->
            <div class="flex flex-wrap gap-2 mb-4">
              <el-tag
                v-for="tagId in share.tagsId"
                :key="tagId"
                size="small"
                effect="plain"
                class="cursor-pointer hover:scale-105 transition-transform duration-300"
                @click.stop="filterByTag(tagId)"
              >
                {{ getTagName(tagId) }}
              </el-tag>
            </div>

            <!-- 互动栏 -->
            <div class="flex items-center gap-6 text-gray-500">
              <button 
                class="flex items-center gap-1 hover:text-blue-600 transition-colors duration-300"
              >
                <el-icon><View /></el-icon>
                <span>{{ share.viewCount || 0 }} 浏览</span>
              </button>
              <button 
                class="flex items-center gap-1 hover:text-blue-600 transition-colors duration-300"
                @click.stop="navigateToDetail(share.shareId)"
              >
                <el-icon><ChatRound /></el-icon>
                <span>{{ share.commentCount || 0 }} 评论</span>
              </button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="mt-8 flex justify-center">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 发布对话框 -->
    <el-dialog
      v-model="showPublishDialog"
      title="发布分享"
      width="600px"
      destroy-on-close
    >
      <el-form 
        ref="publishFormRef"
        :model="publishForm"
        :rules="publishRules"
        label-width="80px"
      >
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="publishForm.content"
            type="textarea"
            :rows="4"
            placeholder="分享你的经验和想法..."
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
            v-model="publishForm.tags"
            multiple
            placeholder="选择标签"
            class="w-full"
          >
            <el-option
              v-for="tag in tagOptions"
              :key="tag.tagId"
              :label="tag.tagName"
              :value="tag.tagId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelPublish">取消</el-button>
          <el-button type="primary" :loading="publishing" @click="handlePublish">
            发布
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  ChatRound,
  View,
  ChatLineSquare
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
import { 
  getShareList, 
  getShareByTag, 
  getAllTags, 
  addShare
} from '@/api/share'
import { useUserStore } from '@/store/user'

dayjs.extend(relativeTime)
dayjs.locale('zh-cn')

const router = useRouter()
const userStore = useUserStore()

// 状态数据
const loading = ref(false)
const searchQuery = ref('')
const selectedTags = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showPublishDialog = ref(false)
const publishing = ref(false)
const shareList = ref([])
const tagOptions = ref([])
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 发布表单
const publishFormRef = ref(null)
const publishForm = ref({
  content: '',
  tags: []
})

// 表单验证规则
const publishRules = {
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '内容长度在 10 到 1000 个字符', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请选择至少一个标签', trigger: 'change' },
    { type: 'array', max: 3, message: '最多选择 3 个标签', trigger: 'change' }
  ]
}

// 获取用户头像
const getUserAvatar = (share) => {
  // 可以根据实际情况获取用户头像，这里使用默认头像
  return defaultAvatar
}

// 获取标签名称
const getTagName = (tagId) => {
  const tag = tagOptions.value.find(t => t.tagId === tagId)
  return tag ? tag.tagName : tagId
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return dayjs(time).fromNow()
}

// 获取分享列表
const fetchShareList = async () => {
  loading.value = true
  try {
    const res = await getShareList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value
    })
    
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取分享列表失败')
    }
  } catch (error) {
    console.error('获取分享列表失败:', error)
    ElMessage.error('获取分享列表失败')
  } finally {
    loading.value = false
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await getAllTags()
    if (res.code === 0 || res.code === 200) {
      tagOptions.value = res.data || []
    } else {
      console.error('获取标签列表失败:', res.message)
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 根据标签筛选
const filterByTagId = async (tagId) => {
  loading.value = true
  try {
    const res = await getShareByTag(tagId)
    if (res.code === 0 || res.code === 200) {
      shareList.value = res.data || []
      total.value = shareList.value.length
    } else {
      ElMessage.error(res.message || '获取标签分享失败')
    }
  } catch (error) {
    console.error('获取标签分享失败:', error)
    ElMessage.error('获取标签分享失败')
  } finally {
    loading.value = false
  }
}

// 根据标签筛选
const filterByTag = (tagId) => {
  if (!selectedTags.value.includes(tagId)) {
    selectedTags.value = [tagId]
    filterByTagId(tagId)
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchShareList()
}

// 处理发布点击
const handlePublishClick = () => {
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    return
  }
  showPublishDialog.value = true
}

// 处理发布
const handlePublish = async () => {
  if (!publishFormRef.value) return
  
  try {
    await publishFormRef.value.validate()
    publishing.value = true
    
    const data = {
      userId: userStore.userId,
      createBy: userStore.username,
      content: publishForm.value.content,
      tags: publishForm.value.tags
    }
    
    const res = await addShare(data)
    
    if (res.code === 0 || res.code === 200) {
      ElMessage.success('发布成功')
      showPublishDialog.value = false
      resetPublishForm()
      fetchShareList()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败')
  } finally {
    publishing.value = false
  }
}

// 重置发布表单
const resetPublishForm = () => {
  publishForm.value = {
    content: '',
    tags: []
  }
  if (publishFormRef.value) {
    publishFormRef.value.resetFields()
  }
}

// 取消发布
const cancelPublish = () => {
  showPublishDialog.value = false
  resetPublishForm()
}

// 导航到详情页
const navigateToDetail = (id) => {
  router.push(`/share/${id}`)
}

// 导航到用户主页
const navigateToUserProfile = (userId) => {
  router.push(`/user/${userId}`)
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchShareList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchShareList()
}

// 监听标签变化
watch(selectedTags, (tags) => {
  if (tags.length > 0) {
    filterByTagId(tags[0])
  } else {
    fetchShareList()
  }
})

onMounted(() => {
  fetchTags()
  fetchShareList()
})
</script>

<style scoped>
.post-card {
  position: relative;
  overflow: hidden;
}

.post-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #3b82f6, #60a5fa, #93c5fd);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.post-card:hover::before {
  opacity: 1;
}

.search-input :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(59, 130, 246, 0.1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper:hover),
.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: rgba(59, 130, 246, 0.3);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.tag-select :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(8px);
  border: 1px solid rgba(59, 130, 246, 0.1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.tag-select :deep(.el-input__wrapper:hover),
.tag-select :deep(.el-input__wrapper.is-focus) {
  border-color: rgba(59, 130, 246, 0.3);
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

/* 动画效果 */
@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

.animate-gradient {
  background-size: 200% 200%;
  animation: gradient 15s ease infinite;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background-color: rgba(156, 163, 175, 0.3);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background-color: rgba(156, 163, 175, 0.5);
}
</style> 